/**
	Python scripting example
	This plugin demonstrates how python can be used with llamabot
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <python2.6/Python.h>

#include "plugin.h"

static struct plugin *plugin_t;
static PyObject *main_dict;
static PyObject *handle;

static PyObject * send_message( PyObject *self, PyObject *args )
{
		char *msg = NULL;

    if( !PyArg_ParseTuple( args, "s", &msg ) )
    	return NULL;

		plugin_t->send_message( msg );

    return NULL;
}

static PyMethodDef IRCMethods[] = {
    {"send_message", send_message, METH_VARARGS,
     "Forward a message to the output queue"},
    {NULL, NULL, 0, NULL}
};

void handle_msg( char *msg ) 
{
	printf("Python plugin: %s\n", msg );

	PyObject_CallFunction( handle, "s", msg );
}

struct plugin * new_plugin() 
{
	plugin_t = (struct plugin*) malloc( sizeof( struct plugin ) );
	if ( plugin_t == NULL ) {
		fprintf( stderr, "Python1 plugin allocation failed, out of memory. \n" );		
		return NULL;
	}

	plugin_t->id = "Python1 plugin";
	plugin_t->handle_msg = handle_msg;

	Py_Initialize();

	PyObject *main_module = PyImport_AddModule("__main__");
	main_dict =  PyModule_GetDict(main_module);

	Py_InitModule("IRC", IRCMethods);
	//PyImport_Import( PyString_FromString("IRC") );
	
	FILE* file_1 = fopen("file1.py", "r"); //Yes, file name is hard coded ;)
	PyRun_File(file_1, "file1.py",				//This can be changed later
        	   Py_file_input,
           	 main_dict, main_dict);

	handle = PyDict_GetItemString( main_dict, "handle_msg" );

	return plugin_t;
}


